package com.example.mqttdemo.controller;

import com.example.mqttdemo.entity.dto.LedDto;
import com.example.mqttdemo.entity.vo.MqttStatusVO;
import com.example.mqttdemo.entity.vo.PublishMessageVO;
import com.example.mqttdemo.result.Result;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;


@RequestMapping("/api")
@RestController
public class ApiController {

    @Autowired
    private MqttClient mqttClient;


    /**
     * 获取服务状态信息
     * 该接口用于返回当前服务的运行状态以及MQTT的连接状态
     *
     * @return 返回包含服务运行状态和MQTT连接状态的字符串
     */
    @GetMapping("/status")
    public Result getStatus() {
        MqttStatusVO statusVO = new MqttStatusVO();
        boolean connected = mqttClient.isConnected();
        if (connected) {
            statusVO.setMqttConnected(connected);
            statusVO.setServiceStatus("运行正常");
            statusVO.setMqttStatus("连接正常");
            statusVO.setTimestamp(LocalDateTime.now());
            return Result.success(statusVO, "MQTT连接成功");
        } else {
            return Result.error("MQTT连接失败");
        }
    }


    /**
     * 下发消息到MQTT主题
     * 该接口用于将指定的消息发布到MQTT的指定主题上，支持设置默认主题。
     *
     * @return 发布成功时返回"Message published to topic: "加上主题名；发布失败时返回错误信息
     * 默认为"device/led/control"
     */
    @PostMapping("/publish")
    public Result publishMessage(@RequestBody LedDto ledDto) {
        PublishMessageVO publishMessageVO = new PublishMessageVO();
        try {
            MqttMessage mqttMessage = new MqttMessage(ledDto.getMessage().getBytes());
            mqttMessage.setQos(1);
            mqttClient.publish(ledDto.getTopic(), mqttMessage);
            publishMessageVO.setTopic(ledDto.getTopic());
            publishMessageVO.setMessage(ledDto.getMessage());
            publishMessageVO.setTimestamp(LocalDateTime.now());
            return Result.success(publishMessageVO, "消息发布成功");
        } catch (MqttException e) {
            return Result.error("消息发布失败: " + e.getMessage());
        }
    }
}
